package socket

import (
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"log/slog"
	"net/http"
	"time"
)

var (
	width   int
	height  int
	quality int = 50
	ticker      = time.NewTicker(time.Millisecond * 100)
)

func Run(address string) {
	hub := newHub()
	go desktop()
	go hub.run()
	h := new(WebSocketHandler)
	hub.SetHandle(h.handle)

	engine := gin.Default()
	router := engine.Group("/socket")
	router.GET("/:group", handle)

	err := engine.Run(address)
	if err != nil {
		slog.Error("ListenAndServe: ", err)
	}
}

func handle(c *gin.Context) {
	grader := websocket.Upgrader{
		CheckOrigin: func(r *http.Request) bool {
			return true
		},
		Subprotocols: []string{c.GetHeader("Sec-WebSocket-Protocol")},
	}
	conn, err := grader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		slog.Error("连接异常：%s", c.Param("group"))
		return
	}
	group := c.Param("group")
	client := &Client{hub: hub, conn: conn, send: make(chan []byte, 256), group: group}
	client.hub.register <- client
	go client.read()
}
